import express from 'express'
import axios from 'axios'
import qs from 'qs'

// Create express router
const router = express.Router()

const axiosServer = axios.create({
  baseURL: 'http://app.w3cstudy.cc'
  // baseURL: 'http://192.168.1.24:8080'
})

// Transform req & res to have the same API as express
// So we can use res.status() & res.json()
const app = express()
router.use((req, res, next) => {
  Object.setPrototypeOf(req, app.request)
  Object.setPrototypeOf(res, app.response)
  req.res = res
  res.req = req
  next()
})

// Add POST - /api/login
router.post('/login', (req, res) => {
  console.log(req.method, req.body)
  // console.log('server')
  // if (req.body.username === 'demo' && req.body.password === 'demo') {
  //   req.session.authUser = { username: 'demo' }
  //   return res.json({ username: 'demo' })
  // }
  // res.status(401).json({ message: 'Bad credentials' })

  async function login() {
    const {
      data
    } = await axiosServer.post('/bm/opera/login', qs.stringify({
      account: req.body.account,
      userPassword: req.body.userPassword
    }), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    return data
  }

  login().then(function (data) {
    // 把token存储到cookie中
    // console.log('login', data)
    // const { token } = data
    // console.log('token', token)
    if (data.code == 200) {
      req.session.authUser = data.detail
      res.cookie('authUser', data.detail, {
        maxAge: 1000 * 60 * 30
      })
      //   maxAge: 60000 * 60 * 24
      // req.session.authUser = data
    }
    return res.json(data)
  })
})

// Add POST - /api/logout
router.post('/logout', (req, res) => {
  // delete req.session.authUser
  // res.json({
  //   ok: true
  // })
  req.session.authUser = null
  // delete req.session.authUser
  res.json({
    code: 200
  })
})

router.all('/bm/*', (req, res) => {
  // const serverUrl = 'http://192.168.1.24:8080'
  const originalUrl = req.originalUrl.substr(4, req.originalUrl.length)
  const url = originalUrl
  console.log(req.method, originalUrl)
  if (req.method == 'GET') {
    // GET
    reqGet(url).then(data => {
      return res.json(data)
    })
  } else {
    if (req.method == 'POST') {
      // POST
      reqPost(url, req.body).then(data => {
        return res.json(data)
      })
    } else {
      return res.json({
        error: '你特么的写错代码了！'
      })
    }
  }
})

async function reqPost(url, postdata) {
  const {
    data
  } = await axiosServer.post(url, qs.stringify(postdata), {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  })
  return data
}

async function reqGet(url) {
  const {
    data
  } = await axiosServer.get(url)
  return data
}

// Export the server middleware
export default {
  path: '/api',
  handler: router
}
